package com.example.hash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class ShardRouter {

    private static final int NUM_SHARDS = 4; // 假设我们有4个分片

    /**
     * 根据用户ID计算并返回该用户数据所在的分片号。
     * @param userId 用户ID
     * @return 分片号
     */
    public int calculateShardForUserId(String userId) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(userId.getBytes());
            long hashValue = ((long)(hash[0] & 0xFF) << 56)
                    | ((long)(hash[1] & 0xFF) << 48)
                    | ((long)(hash[2] & 0xFF) << 40)
                    | ((long)(hash[3] & 0xFF) << 32)
                    | ((long)(hash[4] & 0xFF) << 24)
                    | ((hash[5] & 0xFF) << 16)
                    | ((hash[6] & 0xFF) << 8)
                    | (hash[7] & 0xFF);
            System.out.println("long hash value: "+hashValue);
            return Math.abs((int) hashValue) % NUM_SHARDS;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 algorithm not found", e);
        }
    }

    public static void main(String[] args) {
        ShardRouter router = new ShardRouter();
        System.out.println("User ID 12345 should be in shard: " + router.calculateShardForUserId(UUID.randomUUID().toString()));
    }
}